package com.liwenfeng.diancanspringboot.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.liwenfeng.diancanspringboot.common.context.BaseContext;
import com.liwenfeng.diancanspringboot.common.exception.LoginFailedException;
import com.liwenfeng.diancanspringboot.common.exception.OrderBusinessException;
import com.liwenfeng.diancanspringboot.common.properties.WeChatProperties;
import com.liwenfeng.diancanspringboot.common.utils.HttpClientUtil;
import com.liwenfeng.diancanspringboot.mapper.*;
import com.liwenfeng.diancanspringboot.pojo.dto.UserLoginDTO;
import com.liwenfeng.diancanspringboot.pojo.entity.*;
import com.liwenfeng.diancanspringboot.service.OrderService;
import com.liwenfeng.diancanspringboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    private static final String WX_LOGIN_BASE_URL = "https://api.weixin.qq.com/sns/jscode2session";
    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private TurnoverMapper turnoverMapper;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {
        // 获取openId
        String openid = getOpenid(userLoginDTO.getCode());

        if (openid == null) {
            throw new LoginFailedException("登录失败");
        }

        User user = userMapper.getByOpenid(openid);
        if (user == null) {
            user = new User();
            user.setOpenid(openid);
            user.setCreateTime(LocalDateTime.now());
            userMapper.insert(user);
        }

        return user;
    }

    // 按桌号获取流水单id（手机端user模块）（浏览器端）
    public List<Long> getTurnoverIds(Integer place) {
        if (place == null) {
            throw new LoginFailedException("没桌号重新扫码");
        }
        List<Turnover> turnovers = turnoverMapper.getTurnovers(place);
        if (turnovers.size() >1) {
            throw new OrderBusinessException("有异常，当前桌有多个流水单");
        }
        if (turnovers.size() == 0) {
            return List.of();
        }
        return List.of(turnovers.get(0).getId(), turnovers.get(0).getUserId());
    }

    @Override
    @Transactional
    public List<Long> createTurnover(Turnover turnover) {
        List<Turnover> turnovers = turnoverMapper.getTurnovers(turnover.getPlace());
        if (turnovers.size() == 0) {

            turnover.setNumber(System.currentTimeMillis() + "-" + turnover.getPlace());
            turnover.setCreateTime(LocalDateTime.now());
            turnover.setStatus(0);
            turnoverMapper.insert(turnover);

            // 向订单表插入1条数据
            Dish dish = dishMapper.getByName("餐具");
            Orders orders = new Orders();
            orders.setTurnoverId(turnover.getId());
            orders.setOrderTime(LocalDateTime.now());
            orders.setNumber(String.valueOf(System.currentTimeMillis()));
            orders.setUserId(turnover.getUserId());
            orders.setAmount(BigDecimal.valueOf(dish.getPrice().doubleValue() * turnover.getPeople()));
            String autoAccept = orderService.getAutoAccept();
            if (autoAccept.equals("1")) {
                orders.setStatus(Orders.CONFIRMED);
            } else {
                orders.setStatus(Orders.TO_BE_CONFIRMED);
            }

            orderMapper.insert(orders);

            // 向订单明细表插入n条数据

            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setName("餐具");
            orderDetail.setImage(dish.getImage());
            orderDetail.setDishId(dish.getId());
            orderDetail.setNumber(turnover.getPeople());
            orderDetail.setAmount(dish.getPrice());
            orderDetail.setOrderId(orders.getId());
            orderDetail.setPlace(turnover.getPlace());
            orderDetail.setStatus(OrderDetail.TO_BE_SEND);

            ArrayList<OrderDetail> orderDetails = new ArrayList<>();
            orderDetails.add(orderDetail);
            orderDetailMapper.insertBatch(orderDetails);

            return List.of(turnover.getId(), turnover.getUserId());
        }
        return List.of(turnovers.get(0).getId(), turnovers.get(0).getUserId());
    }

    @Override
    public Turnover getTurnoverById(Long turnoverId) {
        Turnover turnover = turnoverMapper.getById(turnoverId);
        return turnover;
    }

    private String getOpenid(String code) {
        HashMap<String, String> map = new HashMap<>();
        map.put("appid", weChatProperties.getAppid());
        map.put("secret", weChatProperties.getSecret());
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");
        String result = HttpClientUtil.doGet(WX_LOGIN_BASE_URL, map);
        JSONObject jsonObject = JSON.parseObject(result);
        String openid = jsonObject.getString("openid");
        return openid;
    }

    ;
}
